use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use dashmap::DashMap;
use tracing::{info, error, debug};

use crate::error::{Result, ModbusCollectorError};

/// 数据点
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataPoint {
    pub point_id: String,
    pub device_id: String,
    pub name: String,
    pub value: f64,
    pub timestamp: DateTime<Utc>,
    pub quality: DataQuality,
}

/// 数据质量
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DataQuality {
    Good,
    Bad,
    Uncertain,
}

/// 设备状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceStatus {
    pub device_id: String,
    pub online: bool,
    pub last_communication: Option<DateTime<Utc>>,
    pub error_count: u64,
    pub last_error: Option<String>,
}

/// 内存缓存存储
#[derive(Debug)]
pub struct MemoryStorage {
    // 最新数据点值
    latest_data: DashMap<String, DataPoint>,
    // 设备状态
    device_status: DashMap<String, DeviceStatus>,
    // 历史数据缓存 (有限大小)
    history_cache: Arc<RwLock<HashMap<String, Vec<DataPoint>>>>,
    // 缓存配置
    max_history_per_point: usize,
}

impl MemoryStorage {
    pub fn new() -> Self {
        Self {
            latest_data: DashMap::new(),
            device_status: DashMap::new(),
            history_cache: Arc::new(RwLock::new(HashMap::new())),
            max_history_per_point: 1000, // 每个点位最多缓存1000个历史值
        }
    }
    
    /// 存储数据点
    pub async fn store_data_point(&self, data_point: &DataPoint) -> Result<()> {
        debug!("Storing data point: {} = {}", data_point.point_id, data_point.value);
        
        // 存储最新值
        self.latest_data.insert(data_point.point_id.clone(), data_point.clone());
        
        // 更新设备状态
        self.update_device_status(&data_point.device_id, true, None).await;
        
        // 存储到历史缓存
        let mut history = self.history_cache.write().await;
        let point_history = history.entry(data_point.point_id.clone())
            .or_insert_with(Vec::new);
        
        point_history.push(data_point.clone());
        
        // 限制历史数据大小
        if point_history.len() > self.max_history_per_point {
            point_history.remove(0);
        }
        
        Ok(())
    }
    
    /// 获取最新数据点
    pub fn get_latest_data_point(&self, point_id: &str) -> Option<DataPoint> {
        self.latest_data.get(point_id).map(|entry| entry.clone())
    }
    
    /// 获取设备的所有最新数据点
    pub fn get_device_latest_data(&self, device_id: &str) -> Vec<DataPoint> {
        self.latest_data.iter()
            .filter(|entry| entry.device_id == device_id)
            .map(|entry| entry.clone())
            .collect()
    }
    
    /// 获取所有最新数据点
    pub fn get_all_latest_data(&self) -> Vec<DataPoint> {
        self.latest_data.iter()
            .map(|entry| entry.clone())
            .collect()
    }
    
    /// 获取历史数据
    pub async fn get_history_data(
        &self,
        point_id: &str,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Vec<DataPoint> {
        let history = self.history_cache.read().await;
        
        if let Some(point_history) = history.get(point_id) {
            let mut filtered: Vec<DataPoint> = point_history.iter()
                .filter(|dp| {
                    if let Some(start) = start_time {
                        if dp.timestamp < start {
                            return false;
                        }
                    }
                    if let Some(end) = end_time {
                        if dp.timestamp > end {
                            return false;
                        }
                    }
                    true
                })
                .cloned()
                .collect();
            
            // 按时间排序
            filtered.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
            
            // 限制数量
            if let Some(limit) = limit {
                if filtered.len() > limit {
                    filtered = filtered.into_iter().rev().take(limit).rev().collect();
                }
            }
            
            filtered
        } else {
            Vec::new()
        }
    }
    
    /// 更新设备状态
    pub async fn update_device_status(
        &self,
        device_id: &str,
        online: bool,
        error: Option<String>,
    ) {
        let now = Utc::now();
        
        self.device_status.entry(device_id.to_string())
            .and_modify(|status| {
                status.online = online;
                status.last_communication = Some(now);
                if !online {
                    status.error_count += 1;
                    status.last_error = error.clone();
                }
            })
            .or_insert_with(|| DeviceStatus {
                device_id: device_id.to_string(),
                online,
                last_communication: Some(now),
                error_count: if online { 0 } else { 1 },
                last_error: error,
            });
    }
    
    /// 获取设备状态
    pub fn get_device_status(&self, device_id: &str) -> Option<DeviceStatus> {
        self.device_status.get(device_id).map(|entry| entry.clone())
    }
    
    /// 获取所有设备状态
    pub fn get_all_device_status(&self) -> Vec<DeviceStatus> {
        self.device_status.iter()
            .map(|entry| entry.clone())
            .collect()
    }
    
    /// 清理过期数据
    pub async fn cleanup_expired_data(&self, retention_period: chrono::Duration) -> Result<()> {
        let cutoff_time = Utc::now() - retention_period;
        let mut history = self.history_cache.write().await;
        
        for (_, point_history) in history.iter_mut() {
            point_history.retain(|dp| dp.timestamp > cutoff_time);
        }
        
        info!("Cleaned up expired data older than {}", cutoff_time);
        Ok(())
    }
    
    /// 获取统计信息
    pub async fn get_statistics(&self) -> MemoryStorageStats {
        let history = self.history_cache.read().await;
        let total_history_points: usize = history.values().map(|v| v.len()).sum();
        
        MemoryStorageStats {
            latest_points_count: self.latest_data.len(),
            devices_count: self.device_status.len(),
            total_history_points,
            memory_usage_mb: self.estimate_memory_usage(),
        }
    }
    
    /// 估算内存使用量（MB）
    fn estimate_memory_usage(&self) -> f64 {
        // 粗略估算：每个DataPoint约200字节，每个DeviceStatus约100字节
        let latest_size = self.latest_data.len() * 200;
        let device_status_size = self.device_status.len() * 100;
        // 历史数据需要异步计算，这里使用简化估算
        let history_size = self.latest_data.len() * self.max_history_per_point * 200;
        
        (latest_size + device_status_size + history_size) as f64 / (1024.0 * 1024.0)
    }
}

/// 内存存储统计信息
#[derive(Debug, Clone, Serialize)]
pub struct MemoryStorageStats {
    pub latest_points_count: usize,
    pub devices_count: usize,
    pub total_history_points: usize,
    pub memory_usage_mb: f64,
}

impl Default for MemoryStorage {
    fn default() -> Self {
        Self::new()
    }
}